import moment from 'moment';
import path from 'path';
import appRoot from 'app-root-path';
import config from '../../etc';
import log from '../log';
import * as util from '../util/index';

const fsExtra = require('fs-extra');

let isBusy;
function removeFiles() {
    return util.resolve().then(() => {
        //查询目录下所有文件，根据时间判断要删除的
        try {
            const dirPath = path.join(appRoot.toString(), config.customersCsvExportDir);
            fsExtra.readdirSync(dirPath).forEach((file) => {
                log.info('customersCsvExportDir file:', file);
                const t = file.split('_')[1];
                const fileDate = `${t.substr(0, 4)}-${t.substr(4, 2)}-${t.substr(6, 2)} ${t.substr(8, 2)}:${t.substr(10, 2)}:${t.substr(12, 2)}`;
                if (moment(fileDate) < moment().add(-1, 'days')) {
                    const delFilePath = path.join(dirPath, file);
                    fsExtra.unlinkSync(delFilePath, (err) => {
                        if (err) {
                            log.error(err);
                        }
                    });
                }
            });
        } catch (e) {
            throw e;
        }
        return true;
    }).catch(err => {
        log.error('delFiles salesman is err----', err);
        return err;
    });
}

function start() {
    if (isBusy) {
        log.info('customersCsvExportDir is Busy');
        return;
    }
    isBusy = 1;
    try {
        removeFiles()
            .then(res => {
                if (res) {
                    log.info('customersCsvExportDir 执行成功');
                }
            })
            .catch(err => {
                log.info('customersCsvExportDir 执行失败', err);
            })
            .then(() => {
                isBusy = 0;
            });
    } catch (e) {
        log.error('customersCsvExportDir error', e);
        isBusy = 0;
    }
}

export default start;
